package com.example.mybaseapp.ui

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.mybaseapp.R
import com.example.mybaseapp.util.audiorecordutil.ContinuousAudioRecorder
import com.example.mybaseapp.util.audiorecordutil.ContinuousAudioRecorder.AudioDataCallback


class AudioRecordActivity : AppCompatActivity() {
    private val RECORD_AUDIO_PERMISSION_REQUEST_CODE: Int = 101
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_audio_record)
//        getPermission()
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }

    private fun getPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf (Manifest.permission.RECORD_AUDIO), RECORD_AUDIO_PERMISSION_REQUEST_CODE)
        } else {
            // 已经有录音权限，可以开始录音
            startRecording();
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode == RECORD_AUDIO_PERMISSION_REQUEST_CODE) {
            if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户同意了录音权限，可以开始录音
                startRecording()
            } else {
                // 用户拒绝了录音权限，可以在这里处理拒绝权限的逻辑
                Log.d("MainActivity", "录音权限被拒绝")
            }
        }
    }

    private fun startRecording() {
        ContinuousAudioRecorder().apply {

            // 开始录音并返回录音数据
            startRecordingAndReturnAudioData(AudioDataCallback { audioData -> // 处理返回的音频数据
                Log.d(
                    "ContinuousAudioRecorder",
                    "Received audio data: " + audioData.size + " bytes"
                )
            })


            // 一段时间后停止录音
            val stopHandler: Handler = Handler(Looper.myLooper()!!)
            stopHandler.postDelayed(Runnable { stopRecording() }, 10000) // 这里在10秒后停止录音
        }
    }
}